package partFour.homeWork.code.Code04;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 基于TCP协议的服务端
 */
public class Server {
    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        Socket s = null;
        ObjectInputStream in = null;
        ObjectOutputStream out = null;
        try {
            // 1 创建服务端的连接
            serverSocket = new ServerSocket(8808);
            System.out.println("等待客户连接！");

            // 2 等待客户端连接
            s = serverSocket.accept();

            // 3 获取从客户端发来的数据
            in = new ObjectInputStream(s.getInputStream());
            UserMessage userMessage = (UserMessage)in.readObject();
            System.out.println("连接客户端 成功！");
            System.out.println("获取到的信息是："+userMessage);

            // 3.1验证信息是否正确
            if ("admin".equals(userMessage.getUser().getName()) &&
                "123456".equals(userMessage.getUser().getPassword())){
                userMessage.setType("success");
            }else {
                userMessage.setType("fail");
            }

            // 4 返回验证的结果
            out = new ObjectOutputStream(s.getOutputStream());
            out.writeObject(userMessage);

        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            //  5 关闭各种流
            if (null != out){
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != in){
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != s) {
                try {
                    s.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != serverSocket) {
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
